import React, { Key, useEffect, useState } from "react";
import { Form, Input, Button, Card, Table, message, Tooltip } from "antd";
import {
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import {
  getHospitalSetListRequest,
  deleteHospitalSetRequest,
  batchRemoveHospitalSetRequest,
} from "@/api/hospital/hospitalSet";
import type {
  hospitalSetSearchParamsType,
  getHospitalSetListItemType,
  getHospitalSetRecordsType,
} from "@/api/hospital/model/hospitalSetTypes";
import style from "./index.module.css";
import { useNavigate } from "react-router-dom";

export default function HospitalSet() {
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const [hospitalSetList, setHospitalSetList] =
    useState<getHospitalSetRecordsType>([]);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(3);
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [search, setSearch] = useState<hospitalSetSearchParamsType>();
  const [reRender, setRerender] = useState(false);
  const [isDisabled, setIsDisabled] = useState(true);
  const [batchIds, setBatchIds] = useState<Key[]>([]);

  useEffect(() => {
    setIsLoading(true);
    const getHosSetList = async () => {
      const result = await getHospitalSetListRequest(page, limit, search);
      setHospitalSetList(result.records);
      setTotal(result.total);
      setIsLoading(false);
    };
    getHosSetList();
  }, [page, limit, search, reRender]);

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      width: 50,
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      dataIndex: "handle",
      width: 80,
      fixed: "right" as "right",
      render(_: any, item: getHospitalSetListItemType) {
        const { id } = item;
        return (
          <div>
            <Tooltip placement="right" title="修改医院">
              <Button
                type="primary"
                shape="round"
                icon={<EditOutlined />}
                onClick={updateHosSetHandle(id)}
              ></Button>
            </Tooltip>
            <Tooltip placement="right" title="删除医院">
              <Button
                type="primary"
                danger
                shape="round"
                icon={<DeleteOutlined />}
                onClick={deleteHospitalHandle(id)}
              ></Button>
            </Tooltip>
          </div>
        );
      },
    },
  ];

  const searchHosSetListHandle = (fieldValue: hospitalSetSearchParamsType) => {
    setSearch(fieldValue);
  };

  const clearSearchHandle = () => {
    setSearch({});
  };

  const pageChangeHandle = (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);
  };

  const rowSelectionChangeHandle = (ids: Key[]) => {
    setIsDisabled(!ids.length);
    setBatchIds(ids);
  };

  const batchRemoveHospitalHandle = (batchIds: Key[]) => {
    return async () => {
      await batchRemoveHospitalSetRequest(batchIds);
      setIsDisabled(true);
      message.success("批量删除成功");
      setRerender(!reRender);
    };
  };

  const deleteHospitalHandle = (id: number) => {
    return async () => {
      await deleteHospitalSetRequest(id);
      message.success("删除成功");
      setRerender(!reRender);
    };
  };

  const addHosSetHandle = () => {
    navigate("/syt/hospital/addhosset");
  };

  const updateHosSetHandle = (id: number) => {
    return () => {
      navigate("/syt/hospital/updatehosset", {
        state: {
          id,
        },
      });
    };
  };

  return (
    <div className={style.mr}>
      <Card>
        <Form
          name="basic"
          wrapperCol={{ span: 30 }}
          layout="inline"
          autoComplete="off"
          form={form}
          onFinish={searchHosSetListHandle}
        >
          <Form.Item name="hosname">
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item name="hoscode">
            <Input placeholder="医院编号" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button onClick={clearSearchHandle} type="default" htmlType="reset">
              清空
            </Button>
          </Form.Item>
        </Form>
        <div className={style.mt}>
          <Button className={style.mr} type="primary" onClick={addHosSetHandle}>
            添加
          </Button>
          <Button
            type="primary"
            disabled={isDisabled}
            danger
            onClick={batchRemoveHospitalHandle(batchIds)}
          >
            批量删除
          </Button>
        </div>
        <Table
          className={style.mt}
          columns={columns}
          rowKey="id"
          dataSource={hospitalSetList}
          scroll={{ x: 1300 }}
          bordered
          loading={isLoading}
          pagination={{
            current: page,
            pageSize: limit,
            total,
            showSizeChanger: true,
            pageSizeOptions: [3, 5, 10],
            showTotal() {
              return `共${total}个医院`;
            },
            onChange: pageChangeHandle,
          }}
          rowSelection={{
            onChange: rowSelectionChangeHandle,
          }}
        />
      </Card>
    </div>
  );
}
